#define  _CRT_SECURE_NO_WARNINGS
class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
        int m = mat.size(), n = mat[0].size();
        queue<pair<int, int>> queue;
        vector<vector<int>> dist(m, vector<int>(n, -1));
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (mat[i][j] == 0)
                {
                    queue.push({ i, j });
                    dist[i][j] = 0;
                }
            }
        }

        while (queue.size())
        {
            auto [r, c] = queue.front(); queue.pop();
            static int dx[4] = { 0,0,1,-1 };
            static int dy[4] = { 1,-1,0,0 };
            for (int i = 0; i < 4; i++)
            {
                int x = r + dx[i], y = c + dy[i];
                if (x >= 0 && x < m && y >= 0 && y < n
                    && dist[x][y] == -1)
                {
                    dist[x][y] = dist[r][c] + 1;
                    queue.push({ x, y });
                }
            }
        }

        return dist;
    }

};